﻿using Cms.Core.Infrastructure.Common;
using log4net;
using log4net.Config;
using log4net.Core;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace Cms.Core.Infrastructure.Log
{
   public  class Log4NetHelper : ILoggerHelper
    {
       
        private readonly ConcurrentDictionary<Type, ILog> _Loggers = new ConcurrentDictionary<Type, ILog>();



        /// <summary>
        /// 获取记录器
        /// </summary>
        /// <param name="source">soruce</param>
        /// <returns></returns>
        private ILog GetLogger(Type source)
        {
          
            if (_Loggers.ContainsKey(source))
            {
                return _Loggers[source];
            }
            else
            {
      
                ILog logger = LogManager.GetLogger(Keys.log4netRepositoryName, source);
                _Loggers.TryAdd(source, logger);
                return logger;
            }
        }


        ///// <summary>
        ///// 错误信息
        ///// </summary>
        ///// <param name="message">message</param>
        ///// <param name="exception">ex</param>
        public void Error<TType>(object message) where TType : Type
        {
            ILog logger = GetLogger(typeof(TType));

            logger.Error(message);
        }



        ///// <summary>
        ///// 错误信息
        ///// </summary>
        ///// <param name="source">source</param>
        ///// <param name="message">message</param>
        ///// <param name="exception">ex</param>
        public void Error<TType>(object message, Exception exception) where TType : Type
        {
            GetLogger(typeof(TType)).Error(message, exception.InnerException);
        }



        public string WriteLog(string throwMsg, Exception ex)
        {
            return $"【自定义错误】：{throwMsg} \r\n【异常类型】：{ex.GetType().Name} \r\n【异常信息】：{ex.Message} \r\n【堆栈调用】：{ex.StackTrace}";
        }

        public string WriteLog(Exception ex)
        {
            return $"【异常类型】：{ex.GetType().Name} \r\n【异常信息】：{ex.Message} \r\n【堆栈调用】：{ex.StackTrace}";
        }

        public void Error(Type type, object message, Exception exception)
        {
            GetLogger(type).Error(message, exception.InnerException);
        }

        public void Error(object source, object message, Exception exception)
        {
            this.Error(source.GetType(),message,exception);
        }

        public void Error(object source, object message)
        {
            GetLogger(source.GetType()).Error(message);
        }

    
    }

  
}
